//
//  ChooseCompanyController1.m
//  HuaRun2
//
//  Created by admin on 2017/11/6.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "ChooseCompanyController1.h"
#import "SearchView.h"
#import "ChooseCountryCell.h"
#import "NormalDZNEmptyDataSouce.h"
#import "CompanyModel.h"

@interface ChooseCompanyController1 ()<UITableViewDelegate, UITableViewDataSource>
//新建公司
@property (nonatomic, strong) UILabel * newCompanyLab;
//公司标签
@property (nonatomic, strong) UILabel * companyLab;
//公司背景视图
@property (nonatomic, strong) UIView * companyBgView;

//关联现有公司
@property (nonatomic, strong) UILabel * relatedCompanyLab;

//公司英
@property (nonatomic, strong) UITextField * englishTF;
//公司中
@property (nonatomic, strong) UITextField * chineseTF;
//搜索框
@property (nonatomic, strong) SearchView * searchView;

//列表
@property (nonatomic, strong) UITableView * tableView;
//数据
@property (nonatomic, strong) NSArray * dataArray;

@end

@implementation ChooseCompanyController1

- (void)viewInit {
    
    self.navigationItem.title = NSLocalizedString(@"chooseCompany",nil);

    [self.view addSubview:self.newCompanyLab];
 
    [self.view addSubview:self.companyBgView];
    [self.view addSubview:self.companyLab];
    [self.view addSubview:self.relatedCompanyLab];

    [self.view addSubview:self.englishTF];
    [self.view addSubview:self.chineseTF];

    self.searchView = [SearchView new];
    [self.view addSubview:_searchView];
    _searchView.backgroundColor = [UIColor whiteColor];
    self.searchView.placeholderStr = NSLocalizedString(@"搜索公司名称", nil);

    [self.view addSubview:self.tableView];
}

- (void)layoutInit {
    weakself(ws);
    [self.newCompanyLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(ws.view).offset(kMargin10);
        make.right.mas_equalTo(ws.view).offset(-kMargin10);
        make.height.mas_equalTo(30);
    }];

    [self.companyBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.view);
        make.height.mas_equalTo(30 * 2);
        make.top.mas_equalTo(ws.newCompanyLab.mas_bottom);
    }];
    
    [self.companyLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.newCompanyLab);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(ws.newCompanyLab.mas_bottom).offset(0);
    }];

    [self.englishTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.companyLab.mas_right).offset(kMargin10);
        make.right.mas_equalTo(ws.view).offset(-kMargin10);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(ws.newCompanyLab.mas_bottom).offset(0);
    }];
    
    [self.chineseTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(ws.englishTF);
        make.top.mas_equalTo(ws.englishTF.mas_bottom).offset(0);
    }];
    
    [self.relatedCompanyLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(ws.newCompanyLab);
        make.top.mas_equalTo(ws.companyBgView.mas_bottom);
    }];

    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view).offset(kMargin10);
        make.right.mas_equalTo(ws.view).offset(-kMargin10);
        make.top.mas_equalTo(ws.relatedCompanyLab.mas_bottom).offset(kMargin10);
    }];

    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view);
        make.top.mas_equalTo(ws.searchView.mas_bottom).offset(0);
    }];

}

- (void)dataInit {
    
    self.current = 1;
    self.size = 10;
    
}

- (void)methodBind {
    [self loadData];
    
    weakself(ws);
    [self nbRightImageName:@"save" title:nil taget:self clickBlock:^(id result) {
        [ws submitMethod];
    }];
    
    [self.tableView headerRefresh:^{
        [ws refreshData];
    }];
    
    self.searchView.clickBlock = ^(id result) {
        [ws searchBtnMethod];
    };
    [self.searchView.textField addTarget:self action:@selector(recoverOriginDataMethod:)
                        forControlEvents:(UIControlEventEditingChanged)];
    self.normalDZNEmptyDataSouce.reloadBlock = ^{
        [ws refreshData];
    };
    
}

#pragma mark - method
- (void)recoverOriginDataMethod:(UITextField *)textField {
    if (textField.text.length == 0) {
        NSLog(@"恢复最初数据");
        [self loadData];
    }else {
        NSLog(@"准备搜索");
    }
}

- (void)loadMoreData {
    self.current++;
    [self loadData];
}

- (void)refreshData {
    self.current = 1;
    [self loadData];
}

//点击搜索按钮时， 页数置1，
- (void)searchBtnMethod {
    self.current = 1;
    
    [self loadData];
}

- (void)loadData {
    
    //    公司参数：orderBy，取值：name create modify，默认为name
    NSString * keyword = [NSString isemptyStr:self.searchView.textField.text] ? @"" : self.searchView.textField.text;
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kAccountListUrl];
    NSDictionary * dic = @{@"current": @(self.current),
                           @"size": @(self.size),
                           @"keyword": keyword,
                           @"orderBy": @"name"
                           };
    weakself(ws);
    
    [self showActivity:kLodingStr];
    
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        
        [ws.tableView endHeaderRefresh];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showWithText:[NSString showStringWithStr:object[@"msg"]]];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[CompanyModel class] json:object[@"list"]];
        
        ws.dataArray = ws.current == 1 ? array : [ws.dataArray arrayByAddingObjectsFromArray:array];
        [ws.tableView reloadData];
        
        if (array.count >= ws.size) {
            [ws.tableView footerRefresh:^{
                [ws loadMoreData];
            }];
        }else {
            [ws.tableView hiddenFooter];
        }
        
    } failure:^(NSError *error) {
        [ws hideAllAlert];
        
        //        NSLog(@"fail %@", error);
        [ws.tableView endHeaderRefresh];
        [ws showWithText:kNetworkError];
        [ws.normalDZNEmptyDataSouce setDznEmptyStatus:(DZNEmptyStatusFailure)];
    }];
    
}

- (void)submitMethod {
    [self.view endEditing:YES];
    
    [self uploadRelatedCompany];
}

//增加公司
- (void)addNewCompany {
    /*
     name  公司名称，必需
     companyNameChineseC 公司名称(中文)
     */
    
    BOOL isCan = _englishTF.text.length > 0;
    if (!isCan) {
        [self showAlert:NSLocalizedString(@"chooseOrAddCompany",nil)];
        return;
    }
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kAddCompanyUrl];
    NSString * name = [NSString showStringWithStr:_englishTF.text];
    NSString * companyNameChineseC = [NSString showStringWithStr:_chineseTF.text];
    
    NSDictionary * dic = @{@"name": name,
                           @"companyNameChineseC": companyNameChineseC,
                           };
    weakself(ws);
    [self showActivity:NSLocalizedString(@"正在提交", nil)];
    
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        [self showAlert:NSLocalizedString(@"create_success", nil)];

        [ws refreshData];
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}

//关联公司
- (void)uploadRelatedCompany {
    
    BOOL isSelected = NO;
    CompanyModel * companyModel = nil;
    for (CompanyModel * tcompanyModel in self.dataArray) {
        if (tcompanyModel.isSelected) {
            companyModel = tcompanyModel;
            isSelected = YES;
            break;
        }
    }
    
    if (!isSelected) {
        [self addNewCompany];
        return;
    }
    
    self.clickBlock ? self.clickBlock(companyModel): nil;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark  UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChooseCountryCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    CompanyModel * companyModel = self.dataArray[indexPath.row];
    cell.companyModel = companyModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    for (CompanyModel * companyModel in self.dataArray) {
        companyModel.isSelected = NO;
    }
    CompanyModel * companyModel = self.dataArray[indexPath.row];
    companyModel.isSelected = YES;
    [tableView reloadData];

//    CompanyModel * companyModel = self.dataArray[indexPath.row];
//    self.clickBlock ? self.clickBlock(companyModel): nil;
//    [self.navigationController popViewControllerAnimated:YES];

}

#pragma mark setter getter
- (UILabel *)newCompanyLab {
    if (!_newCompanyLab) {
        self.newCompanyLab = [UILabel new];
        _newCompanyLab.textAlignment = NSTextAlignmentLeft;
        _newCompanyLab.font = [UIFont boldSystemFontOfSize:12];
        _newCompanyLab.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _newCompanyLab.text = NSLocalizedString(@"newCompany", nil);
        _newCompanyLab.backgroundColor = kRandomColor;
    }
    return _newCompanyLab;
}

- (UILabel *)companyLab {
    if (!_companyLab) {
        self.companyLab = [UILabel new];
        _companyLab.textAlignment = NSTextAlignmentLeft;
        _companyLab.font = kGeneralFontSize;
        _companyLab.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _companyLab.text = NSLocalizedString(@"公司", nil);
        _companyLab.backgroundColor = kRandomColor;
        _companyLab.numberOfLines = 0;
    }
    return _companyLab;
}

- (UILabel *)relatedCompanyLab {
    if (!_relatedCompanyLab) {
        self.relatedCompanyLab = [UILabel new];
        _relatedCompanyLab.textAlignment = NSTextAlignmentLeft;
        _relatedCompanyLab.font = kGeneralFontSize;
        _relatedCompanyLab.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _relatedCompanyLab.text = NSLocalizedString(@"guanLianCompany", nil);
        _relatedCompanyLab.backgroundColor = kRandomColor;
        _relatedCompanyLab.numberOfLines = 0;
    }
    return _relatedCompanyLab;
}

- (UIView *)companyBgView {
    if (!_companyBgView) {
        self.companyBgView = [UIView new];
        _companyBgView.backgroundColor = [UIColor whiteColor];
    }
    return _companyBgView;
}


- (UITextField *)chineseTF {
    if (!_chineseTF) {
        self.chineseTF = [UITextField new];
        _chineseTF.textAlignment = NSTextAlignmentLeft;
        _chineseTF.font = kGeneralFontSize;
        _chineseTF.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _chineseTF.placeholder = NSLocalizedString(@"inputChName", nil);
    }
    return _chineseTF;
}

- (UITextField *)englishTF {
    if (!_englishTF) {
        self.englishTF = [UITextField new];
        _englishTF.textAlignment = NSTextAlignmentLeft;
        _englishTF.font = kGeneralFontSize;
        _englishTF.textColor = [UIColor colorWithHex:@"3c3c3c"];
        _englishTF.placeholder = NSLocalizedString(@"inputEnName", nil);
        
    }
    return _englishTF;
}

- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[ChooseCountryCell class]
           forCellReuseIdentifier:@"cell"];
        _tableView.tableHeaderView = [UIView new];
        _tableView.tableFooterView = [UIView new];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        //        _tableView.estimatedRowHeight = 213;
        //        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.rowHeight = 50;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

@end
